<template>
  <div>
    <!-- 检查区域（级联） -->
    <a-cascader
      v-on="$listeners"
      v-bind="$attrs"
      :options="options"
      :load-data="loadData"
      placeholder="请选择"
      v-model="currentValue"
      :fieldNames="fieldNames"
    >
      <a-icon v-if="fetching" style="color:#096dd9;" slot="suffixIcon" type="loading" />
    </a-cascader>
  </div>
</template>
<script>
import { setSubItem, set } from '@/api/quality/currency' // api

export default {
  name: 'SelectCheckArea',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number],
      default: () => [],
    },
    // 需要联动的表单名，
    form: {
      type: Object,
      default: function () {
        return {}
      },
    },
    // placeholder
    placeholder: {
      type: String,
      default: function () {
        return '请选择'
      },
    },
    // 自定义 options 中 label name children 的字段
    fieldNames: {
      type: Object,
      default: function () {
        return { label: 'name', value: 'id', children: 'children' }
      },
    },
    // 需要联动的表单名
    keyValue: {
      type: String,
      default: function () {
        return 'projectId'
      },
    },
    // 联动表单值改变时是否清空当前表单值
    isClear: {
      type: Boolean,
      default() {
        return true
      },
    },
    // 是否获取全部列表（包括停用项）
    isAll: {
      type: Boolean,
      default() {
        return true
      },
    },
  },
  data() {
    return {
      fetching: false,
      options: [],
      dataList: [],
    }
  },
  methods: {
    getList(params) {
      if(!params.id){
        return
      }
      this.fetching = true
      if (!this.isAll) {
        params.status = '1'
      }
      setSubItem
        .getList(params)
        .then((res) => {
          this.fetching = false
          if (res.code === 200) {
            this.generateList(res.data?.[0]?.['children'] || [])
            this.options = res.data?.[0]?.['children'] || []
            let e = this.currentValue
            this.getChildren(e)
          }
        })
        .catch((res) => {
          this.fetching = false
        })
    },
    getChildren(e) {
      if (e.length > 0 && this.dataList?.length > 0 && !this.dataList.some((item) => item.id === e[e.length - 1])) {
        let id = e[e.length - 2]
        let option = this.dataList.find((item) => item.id === id)
        this.getDetail(option)
      }
    },
    // 把多级菜单生成单级全部列表
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        node.isLeaf = false
        node.disabled = !node.enabled
        if (node.disabled) {
          node[this.fieldNames.label] += '（停用）'
        }
        if (!this.dataList.some((item) => item.id === node.id)) {
          this.dataList.push(node)
        }
        if (node.children?.['length'] > 0) {
          this.generateList(node.children)
        } else {
          delete node.children
        }
      }
    },
    getDetail(targetOption) {
      targetOption.loading = true
      set
        .getList({
          pageNo: 1,
          pageSize: 1000,
          subItemId: targetOption.id,
        })
        .then((res) => {
          targetOption.loading = false
          if (res.code === 200 && res.data?.['listDutyArea']) {
            // console.log(res.data.listDutyArea)
            targetOption.children = res.data.listDutyArea.map((item) => {
              item[this.fieldNames.label] = item.dutySubcontractor + '-' + item.dutyPeople
              item.disabled = item.status == 0
              if (item.disabled) {
                item[this.fieldNames.label] += '（停用）'
              }
              // if (!this.dataList.some((i) => i.id === item.id)) {
              //   this.dataList.push(item)
              // }
              // console.log(item)
              return item
            })
          }
          this.options = [...this.options]
        })
        .catch((res) => {
          targetOption.loading = false
        })
    },
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      this.getDetail(targetOption)
    },
  },
  computed: {
    // 需要联动的表单值
    attr() {
      return this.form[this.keyValue]
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value || []
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getList({ id: this.attr })
    })
  },
  watch: {
    currentValue(e) {
      this.getChildren(e)
    },
    // 监听联动表单值重置项目列表
    attr(val) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = ''
      }
      // 重置列表
      this.options = []
      val && this.getList({ id: val })
    },
  },
}
</script>
